package com.ishow.noah.modules.service.cycle

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.view.View
import com.ishow.common.widget.PrintView
import com.ishow.noah.R
import com.ishow.noah.databinding.FServiceCycleBinding
import com.ishow.noah.modules.base.mvvm.view.AppBindFragment
import kotlinx.android.synthetic.main.f_service_cycle.*


/**
 * Created by yuhaiyang on 2019-11-08.
 * 探究生命周期
 */
class ServiceCycleFragment : AppBindFragment<FServiceCycleBinding, ServiceCycleViewModel>() {
    private var service: CycleTestService? = null
    private var binder: CycleTestService.TestBinder? = null
    override fun getLayout(): Int = R.layout.f_service_cycle

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        start.setOnClickListener {
            val intent = Intent(view.context, CycleTestService::class.java)
            activity?.startService(intent)
        }

        stop.setOnClickListener {
            val intent = Intent(view.context, CycleTestService::class.java)
            activity?.stopService(intent)
        }
        bind.setOnClickListener {
            bindService()
        }

        unbind.setOnClickListener {
            PrintView.print("ServiceCycleFragment,unbind ")
            activity?.unbindService(connect)
        }

        test.setOnClickListener { testService() }

        PrintView.init(printView)
    }


    private fun bindService() {
        PrintView.print("ServiceCycleFragment, bindService-----")
        val intent = Intent(context, CycleTestService::class.java)
        activity?.bindService(intent, connect, Context.BIND_AUTO_CREATE)
    }

    private val connect = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {
            PrintView.print("ServiceCycleFragment, onServiceDisconnected: ")
        }

        override fun onServiceConnected(name: ComponentName?, _service: IBinder?) {
            PrintView.print("ServiceCycleFragment, onServiceConnected: ")
            if (_service is CycleTestService.TestBinder) {
                binder = _service
                _service.isBinderAlive()
                service = _service.service

            }
        }
    }


    private fun testService() {
        PrintView.print("ServiceCycleFragment, testService: " + (service == null))
        service?.test()
    }

}